package ucadminlogic

import (
	"context"
	"github.com/zeromicro/go-zero/core/logx"
	"navi-mumbai/app/rpc/usercenter/internal/svc"
	"navi-mumbai/app/rpc/usercenter/pb"
	"navi-mumbai/common/xerr"
)

type ChangeBindingLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewChangeBindingLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ChangeBindingLogic {
	return &ChangeBindingLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 创建MarqueeConfig设置
func (l *ChangeBindingLogic) ChangeBinding(in *pb.ChangeBindingReq) (*pb.ChangeBindingResp, error) {
	l.Logger.Infof("ChangeBinding in: %+v", in)
	// 校验pid是否存在, 0表示不存在任何关系
	if in.Pid != 0 {
		userAccount, err := l.svcCtx.UserAccountModel.FindOne(l.ctx, in.Uid)
		if err != nil {
			l.Logger.Errorf("ChangeBinding. UserAccountModel.FindOne error: %+v", err)
			return nil, xerr.NewGrpcErrCodeMsg(xerr.DbError, err.Error())
		}
		if userAccount == nil {
			l.Logger.Errorf("ChangeBinding pid not exist.  in: %+v", in)
			return nil, xerr.NewGrpcErrCodeMsg(xerr.RequestParamError, "pid not exist")
		}
	}
	// 查询邀请记录，判断是否存在
	userInvite, err := l.svcCtx.UserInviteModel.FindOneByUid(l.ctx, in.Uid)
	if err != nil {
		l.Logger.Errorf("ChangeBinding. UserInviteModel.FindOneByUi error: %+v", err)
		return nil, xerr.NewGrpcErrCodeMsg(xerr.DbError, err.Error())
	}
	if userInvite == nil {
		l.Logger.Errorf("ChangeBinding. uid not exist error: %+v", err)
		return nil, xerr.NewGrpcErrCodeMsg(xerr.DbError, "uid not exist")
	}
	// 修改绑定关系，更换pid
	userInvite.Pid = in.Pid
	err = l.svcCtx.UserInviteModel.Update(l.ctx, userInvite)
	if err != nil {
		return nil, xerr.NewGrpcErrCodeMsg(xerr.DbError, err.Error())
	}
	return &pb.ChangeBindingResp{}, nil
}
